package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.controller.BlogController;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import io.lettuce.core.Consumer;
import netscape.security.UserDialogHelper;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private IFollowService followService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 保存探店笔记功能，并且推送给关注我的人
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.ok("博客笔记保存失败");
        }
        //获取关注我的人的id  select id from tb_follow where followUserId = userId
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        //将博客推送给关注我的人
        for (Follow follow : follows) {
            Long userId = follow.getUserId();
            String key = "feed:"+userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }


    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));

        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 查看探店笔记
     */
    @Override
    public Result queryBlogById(Long id) {
        //查询blog
        Blog blog = getById(id);
        if(blog ==null){
            return Result.fail("笔记不存在");
        }
        //查询blog有关的用户
        queryBlogUser(blog);
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    /*查询用户是否点过赞，点过赞会高亮*/
    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return;
        }
        Long userId = user.getId();
        //判断是否点过赞
        String key = "blog:like" + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    /**
     * 博客点赞业务
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //获取当前用户的信息
        Long userId = UserHolder.getUser().getId();
        //判断当前用户是否点过赞  ZSet：ZADD key score number
        String key = "blog:like"+id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //没点过赞
        if(score == null){
            //没点过赞，进行点赞，点赞数+1，保存到ZSet集合当中
            //点赞数+1
            boolean success = update().setSql("liked = liked + 1").eq("id", id).update();
            //保存到set集合当中
            if (success) {  //zadd score number ->代码中  add number score
                stringRedisTemplate.opsForZSet().add(key ,userId.toString(),System.currentTimeMillis());//此时的score是使用时间戳来设置的
            }
        }else{//点过赞
            //点过赞，则取消点赞，点赞数-1，保存到set集合当中
            //取消点赞，点赞数-1，
            boolean success = update().setSql("liked = liked - 1").eq("id", id).update();
            //保存到set集合当中
            if (success) {
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        //返回数据
        return Result.ok();
    }

    /**
     * 查询点赞top5
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        String key = "blog:like"+id;
        //查询zset集合集合中的top5  zrange key 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5 == null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //解析出其中的用户id(把id变成long类型)
        List<Long> ids = top5.stream().map(top -> Long.valueOf(top)).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        //返回
        return Result.ok(userDTOS);
    }



    /**
     * 分页查询用户博客
     * @param userId
     * @return
     */
    @Override
    public Result queryBlogByUserId(Long userId,Integer current) {
        //根据用户进行查询
        Page<Blog> page = query()
                .eq("user_id", userId)
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        //获取当页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    /**
     * 推送关注人的博客
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //获取当前用户的id
        Long userId = UserHolder.getUser().getId();
        //查询收件箱
        String key = "feed:"+userId;
        //reverseRangeByScoreWithScores：从有序集合中按分数倒序获取元素，即从高分到低分返回结果：(key,min,max,offset(上一页有几个相同的score),2(一页出现几个数据))
        Set<ZSetOperations.TypedTuple<String>> typedTuples =
                stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key,0,max,offset,2);
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
        //解析数据：blogId max,offset
        ArrayList<Object> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //获取id
            ids.add(Long.valueOf(typedTuple.getValue()));
            //获取分数(时间戳)
            long time = typedTuple.getScore().longValue();
            if(time == minTime){
                os++;
            }else{
                minTime = time;
                os=1;
            }
        }
        //根据id查询博客
        //解决SQL的in不能排序问题，手动指定排序为传入的ids
        String idsStr = StrUtil.join(",",ids);//将id列表转换为逗号分隔的字符串，
        //5. 根据id查询blog  .last("ORDER BY FIELD(id," + idsStr + ")")=ORDER BY FIELD(id, 5,3,8,1)
        //FIELD() 函数为每个 ID 分配一个位置值：
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idsStr + ")").list();
        for (Blog blog : blogs) {
            //5.1 查询发布该blog的用户信息
            queryBlogUser(blog);
            //5.2 查询当前用户是否给该blog点过赞
            isBlogLiked(blog);
        }
        //封装并且返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }


    /*查询blog有关的用户信息*/
    private void queryBlogUser( Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
